﻿/*
 * Copyright (C) 2010 Proxy Switch <http://proxyswitch.googlecode.com/>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Xml;

namespace ProxySwitch
{
    public partial class Main : Form
    {
        // needed to refresh internet settings
        [DllImport("wininet.dll")]
        public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
        public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
        public const int INTERNET_OPTION_REFRESH = 37;

        // declare strings
        string ProxyAddress;
        string ProxyPort;
        string ProxyExcep;

        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            // keep Main form hidden
            if (FormWindowState.Minimized == WindowState)
                Hide();

            // launch UpdateCheck form
            // will add config option for turning auto updates off
            UpdateCheck UpdateCheckWindow = new UpdateCheck();
            UpdateCheckWindow.Show();
        }

        private void ProxyOnMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (File.Exists("Config.xml"))
                {
                    // load the Config.xml
                    XmlDocument loadDoc = new XmlDocument();
                    loadDoc.Load(Application.StartupPath + "\\Config.xml");

                    // XML settings to strings
                    ProxyAddress = loadDoc.SelectSingleNode("/proxy/address").Attributes["url"].InnerText;
                    ProxyPort = loadDoc.SelectSingleNode("/proxy/port").Attributes["value"].InnerText;
                    ProxyExcep = loadDoc.SelectSingleNode("/proxy/exceptions").Attributes["value"].InnerText;
                    
                    {
                        // open registry key needed
                        RegistryKey InternetSettings = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
                        
                        // write to registry
                        InternetSettings.SetValue("ProxyEnable", 1);
                        InternetSettings.SetValue("ProxyServer", (ProxyAddress) + ":" + (ProxyPort));
                        InternetSettings.SetValue("ProxyOverride", (ProxyExcep));
                        
                        // close key
                        InternetSettings.Close();

                        // refresh internet settings
                        InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
                        InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
                    }

                    MessageBox.Show("The proxy settings have now been turned on!", "Successful!",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    // for now we restart the whole program silently
                    // this is needed as refreshing the internet settings
                    // will only refresh once
                    System.Windows.Forms.Application.Restart();
                }
                else
                {
                    MessageBox.Show("The configuration file could not be found! Please contact the system administrator", "Oh dear!",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            // catch the error output to MessageBox
            catch (System.Exception ErrorCode)
            {
                MessageBox.Show(ErrorCode.Message, "Oh dear!",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ProxyOffMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // open registry key needed
                RegistryKey InternetSettings = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
                        
                // write to registry
                InternetSettings.SetValue("ProxyEnable", 0);
                        
                // close key
                InternetSettings.Close();

                // refresh internet settings
                InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
                InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);

                MessageBox.Show("The proxy settings have now been turned off!", "Successful!",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                // for now we restart the whole program silently
                // this is needed as refreshing the internet settings
                // will only refresh once
                System.Windows.Forms.Application.Restart();
            }

            // catch the error output to MessageBox
            catch (System.Exception ErrorCode)
            {
                MessageBox.Show(ErrorCode.Message, "Oh dear!",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void AboutMenuItem_Click(object sender, EventArgs e)
        {
            // show AboutWindow form
            About AboutWindow = new About();
            AboutWindow.Show();
        }

        private void LicenceMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // show licence
                System.Diagnostics.Process.Start("http://www.gnu.org/licenses/gpl-2.0.txt");
            }
            catch (System.Exception ErrorCode)
            {
                // catch the error output to MessageBox
                MessageBox.Show(ErrorCode.Message, "Oh dear!",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ExitMenuItem_Click(object sender, EventArgs e)
        {
            // confirmation of exit
            DialogResult dlgResult = MessageBox.Show("Are you sure you wish to exit Proxy Switch?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlgResult == DialogResult.Yes)
            {
                Application.Exit();
            }
        }
    }
}